<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="table1"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          row-key="uuid"
          :tree-props="{children: 'data', hasChildren: 'hasChildren'}"
          show-summary
          :cell-class-name="cellClassName"
          :cell-style="cellStyle"
          :summary-method="getSummaries"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" width="70" align="center" />
          <Column
            v-for="(column,index) in tableColumns"
            :key="index"
            :prop="column.prop"
            :is-show="column.isShow"
            :label="column.label"
            :sortable="column.sortable"
            :width="column.width"
            :min-width="column.minWidth"
            :align="column.align"
          />
          <!-- <el-table-column label="交期情况" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.overdueStatusName=='逾期'" class="insufficient_space">
                <svg-icon icon-class="驳回" />
                逾期
              </div>
              <div v-if="scope.row.overdueStatusName=='正常'" class="adequate_space">
                <svg-icon icon-class="通过" />
                正常
              </div>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>

  </div>
</template>

<script>
import { listForSaleCollect, listSaleCollectForExport } from '@/api/saleManage/saleSummaryReport'
import { getInfo } from '@/api/saleManage/saleOrder'
import ShowDetail from '@/views/saleManage/saleOrder/showDetail.vue' // 查看页面
import { getDictSelects } from '@/api/common/common'
export default {
  name: 'ByMaterial',
  data() {
    return {
      loading: true,
      pageId: '销售订单按销售人员汇总表', // 页面唯一标识
      pageExportId: '销售订单按销售人员汇总表导出',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'orderName',
        isAsc: 'desc',
        byColumn: 'orderName'
      },
      totalWord: ['orderNumber', 'taxAllPrice'], // 合计导出字段
      // tableKey: 1,
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 导出表格数据
      tableData2: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'orderName', label: '销售人员', minWidth: '80', isRegular: true },
        // { prop: 'materialCode', label: '物料编码', minWidth: '150' },
        // { prop: 'materialName', label: '物料名称', canOrder: false, minWidth: '100' },
        // { prop: 'materialModel', label: '规格型号', canOrder: false, minWidth: '130' },
        // { prop: 'materialUnitName', label: '物料单位', canOrder: false, minWidth: '80' },
        { prop: 'code', label: '销售订单号', canOrder: false, minWidth: '80' },
        { prop: 'orderNumber', label: '订单数量', align: 'right', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'taxAveragePriceThousandths', label: '含税均价', align: 'right', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'taxAllPriceThousandths', label: '销售额', align: 'right', minWidth: this.SETTINGS.settings_decimalDigits_length }
      ],
      exportTableColumns: [
        { prop: 'orderName', label: '销售人员', minWidth: '80' },
        // { prop: 'materialCode', label: '物料编码', minWidth: '150' },
        // { prop: 'materialName', label: '物料名称', canOrder: false, minWidth: '100' },
        // { prop: 'materialModel', label: '规格型号', canOrder: false, minWidth: '130' },
        // { prop: 'materialUnitName', label: '物料单位', canOrder: false, minWidth: '80' },
        { prop: 'code', label: '销售订单号', canOrder: false, minWidth: '80' },
        { prop: 'orderNumber', label: '订单数量', align: 'right', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'taxAveragePrice', label: '含税均价', align: 'right', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'taxAllPrice', label: '销售额', align: 'right', minWidth: this.SETTINGS.settings_decimalDigits_length }
      ],
      defaultExport: [],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'orderName', label: '销售人员', type: 'input' },
        // { prop: 'materialCode', label: '物料编码', type: 'input' },
        // { prop: 'materialName', label: '物料名称', type: 'input' },
        // { prop: 'materialModel', label: '规格型号', type: 'input' },
        // { prop: 'materialUnit', label: '物料单位', type: 'dict', optionsName: 'statusOptions3' },
        { prop: 'orderGoodsTime', label: '订货日期', type: 'time', isTime: true, clearable: false, hasDefault: true, defaultKey: 'orderTimeDefault' }
      ],
      orderTimeDefault: [], // 存放字段的默认值
      operationData: [ // 右上角的操作按钮
        { label: '批量导出3', perm: '' },
        { label: '页面配置2', perm: '' }
      ],
      equipmentList: [],
      statusOptions: [
        { value: undefined, label: '全部' },
        { value: '4', label: '已通过' },
        { value: '5', label: '执行中' },
        { value: '6', label: '已完成' },
        { value: '7', label: '已关闭' }
      ],
      statusOptions2: [
        { value: undefined, label: '全部' },
        { value: '0', label: '未发货' },
        { value: '1', label: '部分发货' },
        { value: '2', label: '全部发货' }
      ],
      statusOptions3: [],
      statusOptions4: [
        { value: undefined, label: '全部' },
        { value: '1', label: '逾期' },
        { value: '0', label: '正常' }
      ], showKey: [
        {
          name: '基本信息',
          columns: [
            { type: 'form', name: '销售订单号', key: 'code' },
            { type: 'form', name: '制单人员', key: 'orderName' },
            { type: 'form', name: '制单日期', key: 'orderTime' },
            { type: 'form', name: '订单类型', key: 'orderTypeLabel' },
            { type: 'form', name: '客户名称', key: 'customerName' },
            { type: 'form', name: '订货日期', key: 'orderGoodsTime' },
            { type: 'form', name: '合同号', key: 'contractCode' },
            { type: 'form', name: '未税总金额', key: 'allPriceThousandths' },
            { type: 'form', name: '含税总金额', key: 'taxAllPriceThousandths' },
            { type: 'form', name: '税额', key: 'tax' },
            { type: 'file', name: '附件', fileName: 'fileName', fileRealName: 'fileRealName', fileUrl: 'url' },
            { type: 'form', name: '备注', key: 'remark', length: 'double' },
            {
              type: 'table', name: '', key: 'data'
            }
          ]
        },
        {
          name: '客户信息',
          columns: [
            // { type: 'formData', name: '计税方式', key: 'taxTypeLabel' },
            // { type: 'formData', name: '税率%', key: 'taxRateLabel' },
            // { type: 'formData', name: '结算方式', key: 'settlementTypeLabel' },
            // { type: 'formData', name: '结算币别', key: 'settlementCurrencyLabel' },
            { type: 'formData2', name: '交货方式', key: 'deliveryTypeLabel' },
            { type: 'formData2', name: '联系人', key: 'consignee' },
            { type: 'formData2', name: '联系方式', key: 'phone' },
            { type: 'formData2', name: '注意事项', key: 'attentionMatters' },
            { type: 'formData2', name: '收货地址', key: 'deliveryAddress', length: 'double' }
          ]
        },
        {
          name: '审批详情',
          columns: [
            { type: 'review', name: '评审进度', key: 'taskList' }
          ]
        }
      ],
      equipmentList1: [],
      Updata: []
    }
  },
  watch: {
    tableData() {
      this.$nextTick(() => {
        for (const elementNodeListOfElement of document.querySelectorAll('.SaleOrderCodeColumnClass')) {
          if (!elementNodeListOfElement.childNodes[0].childNodes[0].className || elementNodeListOfElement.childNodes[0].childNodes[0].className == 'commonTableColumn') {
            const paddingNode = document.createElement('div')
            paddingNode.className = 'SaleOrderCodeColumnClass_expand'
            paddingNode.innerHTML = ''
            elementNodeListOfElement.childNodes[0].insertBefore(paddingNode, elementNodeListOfElement.childNodes[0].childNodes[0])
          }
        }
      })
    }
  },
  created() {
    this.orderTimeDefault = [this.$moment().startOf('month').format('YYYY-MM-DD') + ' 00:00',
      this.$moment(new Date()).format('YYYY-MM-DD') + ' 23:59']
  },
  mounted() {
    this.getDictSelects()
  },
  methods: {
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 1) {
        return 'SaleOrderCodeColumnClass'
      }
      if (!row.isNotselected) {
        return 'displayNoneClass'
      }
    },
    cellStyle({ row, column }) {
      if (column.property == 'code' && row.code) {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      console.log(row)
      if (row.code) {
        switch (column.property) {
          case 'code':
            this.showDetail(row)
            break
        }
      }
    },
    showDetail(row) {
      getInfo(row.id).then(res => {
        this.$layer.iframe({// 弹框
          content: {
            content: ShowDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              businessId: row.id,
              showData: res.data,
              showKey: this.showKey
            }// props
          },
          area: ['1320px', '700px'],
          title: '查看销售订单', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
      this.$store.dispatch('notification/changeId', 0)
    },
    getList() {
      listForSaleCollect({ ...this.pageData, byColumn: 'orderName' }).then(res => {
        res.data.data.forEach((item) => { item.isNotselected = true })
        this.tableData = res.data.data
        this.total = res.data.total
        this.Updata = res
        this.loading = false
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
          this.$refs.table1.doLayout()
        })
      })
    },
    // 保养级别字典
    getDictSelects() {
      getDictSelects('materialUnitId').then(res => {
        this.statusOptions3 = res.data
        res.data.unshift({ dictCode: undefined, dictLabel: '全部' },)
      })
    },
    getExportData(data) {
      if (data.importIds.length > 0) {
        data.exportIds = data.importIds.split(',')
      } else {
        data.exportIds = []
      }
      return new Promise(function(resolve, reject) {
        listSaleCollectForExport({ ...data, byColumn: 'orderName' }).then(res => {
          console.log(res.data.data)
          resolve(res.data.data)
        //   this.tableData = res.data.dataTable.data
        })
      })
    },
    // 合计行
    getSummaries(param) {
      const {
        columns
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'orderNumber':
            sums[index] = this.Updata.totalOrderNumberThousandths
            break
        }
        switch (column.property) {
          case 'alreadyDeliverNumber':
            sums[index] = this.Updata.alreadyDeliverNumberSum
            break
        }
        switch (column.property) {
          case 'unDeliverNumber':
            sums[index] = this.Updata.unDeliverNumberSum
            break
        }
        switch (column.property) {
          case 'alreadyReturnNumber':
            sums[index] = this.Updata.alreadyReturnNumberSum
            break
        }
        switch (column.property) {
          case 'taxAllPriceThousandths':
            sums[index] = this.Updata.totalTaxAllPriceThousandths
            break
        }
      })
      return sums
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-tooltip{
  display: flex;
}
.main_header{
  .padding_container{
    justify-content: flex-end;
  }
}
/deep/ .SaleOrderCodeColumnClass_expand{
  display: inline-block;
  width: 20px;
  line-height: 20px;
  height: 20px;
  text-align: center;
  margin-right: 3px;
}
/deep/.el-table .displayNoneClass .cell .el-checkbox__inner{
  display: none
}
</style>
